#PyMinecraft本体文件
#导入所需包
from os import environ
#不输出Pygame
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import sys
import time
import pygame
import _thread
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import save
def loadImage(imageName="beau.jpg"):
    """Load an image from a file using PIL.
    This is closer to what you really want to do than the
    original port's crammed-together stuff that set global
    state in the loading method.  Note the process of binding
    the texture to an ID then loading the texture into memory.
    This didn't seem clear to me somehow in the tutorial.
    """
    from PIL.Image import open
    im = open(imageName)
    try:
        ix, iy, image = im.size[0], im.size[1], im.tobytes("raw", "RGBA", 0, -1)
    except SystemError:
        ix, iy, image = im.size[0], im.size[1], im.tobytes("raw", "RGBX", 0, -1)
    # generate a texture ID
    ID = glGenTextures(1)
    # make it current
    glBindTexture(GL_TEXTURE_2D, ID)
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    # copy the texture into the current texture ID
    glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
    # glGenerateMipmap(GL_TEXTURE_2D)
    # return the ID for use
    return ID
verticies = (  # 顶点坐标  瞎写的
    (2, 0, 0),
    (0, 1, 0),
    (0, 1, 1),
    (0, 0, 1)
)

edges = (  # 边的顺序
    (0, 1),
    (0, 2),
    (0, 3),
    (1, 2),
    (2, 3),
    (3, 1)
)
pygame.init()
a = [800,600]
sc = pygame.display.set_mode((int(a[0]),int(a[1])),pygame.RESIZABLE)
pygame.display.set_caption("Python Minecraft 1.0")
red = pygame.color.Color("#DC143C")
loading = 0
loop = 0
loading_over = False
Loadover___ =False
ingame = False
#ingame = True
def Block(textrule):
    verticies = (
        (1, -1, -1),
        (1, 1, -1),
        (-1, 1, -1),
        (-1, -1, -1),
        (1, -1, 1),
        (1, 1, 1),
        (-1, -1, 1),
        (-1, 1, 1)
    )
    edges = (
        (0, 1),
        (0, 3),
        (0, 4),
        (2, 1),
        (2, 3),
        (2, 7),
        (6, 3),
        (6, 4),
        (6, 7),
        (5, 1),
        (5, 4),
        (5, 7)
    )
    texr = [loadImage(textrule+"_top.png"),loadImage(textrule+".png")]
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()
class inputbox:
    class _Inputbox():
        def __init__(self,default_content="",text=""):
            import tkinter as TK
            self._root = TK.Tk()
            self.get = ""  # 自定义属性
            sw = self._root.winfo_screenwidth()  # 获取桌面宽度
            sh = self._root.winfo_screenheight()  # 获取桌面高度
            width = 300  # 输入框的宽度
            height = 60  # 输入框的高度
            startx = (sw - width) / 2  # 起始x坐标（居中显示用)
            starty = (sh - height) / 2  # 起始y坐标
            # if Turtle._screen is not None:
            #   scheight = Turtle._screen.window_height()
            #   starty = starty + scheight//2 -height//2 - 20
            self._root.geometry("%dx%d%+d%+d" % (width, height, startx, starty))
            self._root.title("输入")
            self.label_file_name = TK.Label(self._root, text=text)
            self.label_file_name.pack()
            default_value = TK.StringVar()
            default_value.set(default_content)
            self.entry = TK.Entry(self._root, width=36,textvariable = default_value)
            self.entry.pack(padx=10, side=TK.LEFT)
            self.entry.focus()
            self.entry.bind("<Return>", self.getinput)  # 绑定回车键
            self.submit = TK.Button(self._root, text='确定', command=self.getinput)  # 确定按钮
            self.submit.pack(padx=10, side=TK.RIGHT)  # 放在右边
            self._root.mainloop()
        def getinput(self, a):
            self.get = self.entry.get()
            self._root.destroy()
def sound():
    while True:
        pygame.mixer.init()
        pygame.mixer.music.load(r"..\\..\\Resources\\music\\C418 - Minecraft.mp3")
        pygame.mixer.music.play(start=0.0)
        time.sleep(254)
        pygame.mixer.stop()
class mcbut:
    def __init__(self,image,image_h,text,font,size):
        self.tex = text
        self.image = pygame.image.load(image)
        self.image_h = pygame.image.load(image_h)
        self.font = pygame.font.Font(font,size)
        self.text = self.font.render(text,True,pygame.Color("white"))
    def blit(self,sc,xy):
        w = self.image.get_rect().width
        h = self.image.get_rect().height
        tw = self.text.get_rect().width
        th = self.text.get_rect().height
        txy = (xy[0] + w / 2 - tw / 2, xy[1] + h / 2 - th / 2)
        x, y = pygame.mouse.get_pos()
        if x >= xy[0] and y >= xy[1] and x <= xy[0]+w and y <= xy[1]+h:
            self.b = True
            sc.blit(self.image_h, xy)
            self.text = self.font.render(self.tex, True, pygame.color.Color("yellow"))
        else:
            self.b = False
            sc.blit(self.image,xy)
            self.text = self.font.render(self.tex, True, pygame.color.Color("white"))
        sc.blit(self.text,txy)
    def is_down(self,event):
            if event.type == pygame.MOUSEBUTTONDOWN and self.b:
                return True
            else:
                return False
    def change_size(self,size):
        self.image = pygame.transform.scale(self.image,size)
        self.image_h = pygame.transform.scale(self.image_h,size)
class ibtn:
    def __init__(self,Size,font,fontsize,why):
        self.Size = Size
        self.font = pygame.font.Font(font,fontsize)
        self.why = why
        self.text_ = "新的世界"
    def draw(self,sc,xy,event):
        w = self.Size[0]
        h = self.Size[1]
        x, y = pygame.mouse.get_pos()
        pygame.draw.rect(sc,pygame.color.Color("black"),(xy,self.Size))
        if x >= xy[0] and y >= xy[1] and x <= xy[0]+w and y <= xy[1]+h:
            if event.type == pygame.MOUSEBUTTONDOWN:
                i = inputbox._Inputbox(self.text_,self.why)
                self.text_ = i.get
        self.text = self.font.render(self.text_, True, pygame.color.Color("white"))
        tw = self.text.get_rect().width
        th = self.text.get_rect().height
        txy = (xy[0] + w / 2 - tw / 2, xy[1] + h / 2 - th / 2)
        sc.blit(self.text, txy)
Csaves = mcbut("..\\..\\Resources\\gui\\button.png","..\\..\\Resources\\gui\\button_h.png","创建存档","..\\..\\Resources\\font\\Minecraft.ttf",15)
start = mcbut("..\\..\\Resources\\gui\\button.png","..\\..\\Resources\\gui\\button_h.png","单人游戏","..\\..\\Resources\\font\\Minecraft.ttf",15)
Done = mcbut("..\\..\\Resources\\gui\\button.png","..\\..\\Resources\\gui\\button_h.png","确定","..\\..\\Resources\\font\\Minecraft.ttf",15)
Cancel = mcbut(r"..\\..\\Resources\\gui\\button.png","..\\..\\Resources\\gui\\button_h.png","取消","..\\..\\Resources\\font\\Minecraft.ttf",15)
Font = pygame.font.Font("..\\..\\Resources\\font\\Minecraft.ttf",15)
back = pygame.image.load("..\\..\\Resources\\gui\\presets\\isles.png")
Mojang = pygame.image.load("..\\..\\Resources\\gui\\title\\mojang.png")
Load = pygame.image.load("..\\..\\Resources\\gui\\title\\loading.png")
Minecraft = pygame.image.load("..\\..\\Resources\\gui\\Minecraft.png")
Back = pygame.image.load("..\\..\\Resources\\gui\\options_background.png")
Back2 = pygame.image.load("..\\..\\Resources\\gui\\options_background2.png")
Cant = Font.render("无法创建更多世界！",True,pygame.color.Color("white"))
size = (128,128)
Back = pygame.transform.scale(Back,size)
Back2 = pygame.transform.scale(Back2,size)
image2_x_ = 204
image2_y_ = 24
image2x = 500
image2y = 53
memu = True
create_world = False
saves_list = []
saves_list_render = {}
cant_display = False
def cant():
    global cant_display
    cant_display = True
    time.sleep(5)
    cant_display = False
while True:
    Now_saves_Name = ""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
        elif event.type == pygame.VIDEORESIZE:
            xSize = event.dict['size'][0]
            ySize = event.dict['size'][1]
            if not ingame:
                sc = pygame.display.set_mode((xSize, ySize),pygame.RESIZABLE)
            else:
                sc = pygame.display.set_mode((xSize, ySize), pygame.RESIZABLE|pygame.OPENGL)
    if not ingame:
        sc.fill((255, 255, 255))
        scy = sc.get_rect().bottom
        scx = sc.get_rect().right
        if not loading_over:
            imagex = 512
            imagey = 80
            image2x = 500
            image2y = 53
            pygame.mouse.set_visible(False)
            sc.blit(Mojang,((scx-imagex)/2,((scy-imagey)/2)-scy*0.2))
            sc.blit(Load,((scx - image2x) / 2, ((scy - image2y)/2) - scy*0.01))
            pygame.draw.rect(sc, red, [((scx - image2x) / 2)+6, ((scy - image2y)/2)+8 - scy*0.01, loading, 16])
            if loop<=300 or loop>450:
                if loading != 495:
                    loading += 1
                else:
                    time.sleep(1)
                    loading_over = True
                    sc.fill((0, 0, 0))
                    #_thread.start_new_thread(sound,())
            else:
                if loop == 450:
                    loading += 30
            loop += 1
        else:
            if memu:
                pygame.mouse.set_visible(True)
                back = pygame.transform.scale(back, (xSize, ySize))
                sc.blit(back,(0,0))
                MCx = 548
                MCy = 88
                sc.blit(Minecraft,((scx - MCx) / 2, ((scy - MCy)/2) - scy*0.2))
                start.blit(sc,((scx - image2x) / 2, ((scy - image2y)/2) - scy*0.01))
                if start.is_down(event):
                    memu = False
            else:
                if not create_world:
                    for i in range(round(scy/16)):
                        for i2 in range( round(scx / 16)):
                            if i%2 == 0:
                                sc.blit(Back,(i2*128,i*128))
                            else:
                                sc.blit(Back2, (i2 * 128, i * 128))
                    Now = 0
                    for i in saves_list_render.values():
                        Now += 42
                        i.change_size((300,32))
                        i.blit(sc,(((scy - i.image.get_rect().width) / 2),Now))
                        print(saves_list_render)
                    image2_x = 300
                    image2_y = 32
                    Csaves.change_size((image2_x,image2_y))
                    Csaves.blit(sc, (((scx - image2_x) / 2) - scx * 0.28 , ((scy - image2_y) / 2) + scy * 0.2))
                    if Csaves.is_down(event):
                        create_world = True
                        Saves = ibtn((204, 24), r"..\\..\\Resources\\font\\Minecraft.ttf", 15, "存档名字：")
                    for i in saves_list_render.keys():
                        if saves_list_render[i].is_down(event):
                            Now_saves_Name = i
                            ingame = True
                            Loadover___ = True
                else:
                    for i in range(round(scy/16)):
                        for i2 in range( round(scx / 16)):
                            if i%2 == 0:
                                sc.blit(Back,(i2*128,i*128))
                            else:
                                sc.blit(Back2, (i2 * 128, i * 128))
                    Saves.draw(sc,((scx - image2_x_) / 2, ((scy - image2_y_)/2) - scy*0.01),event)
                    savename = Saves.text_
                    image2_x = 300
                    image2_y = 32
                    Cancel.change_size((image2_x,image2_y))
                    Done.change_size((image2_x,image2_y))
                    Done.blit(sc, (((scx - image2_x) / 2) - scx * 0.28, ((scy - image2_y) / 2) + scy * 0.3))
                    Cancel.blit(sc, (((scx - image2_x) / 2) + scx * 0.25, ((scy - image2_y) / 2) + scy * 0.3))
                    if Done.is_down(event):
                        if not savename in saves_list:
                            if len(saves_list) == 5:
                                _thread.start_new_thread(cant,())
                            else:
                                saves_list_render[savename] = mcbut(r"..\\..\\Resources\\gui\\button.png", r"..\\..\\Resources\\gui\\button_h.png",savename,r"..\\..\\Resources\\font\\Minecraft.ttf", 15)
                                saves_list.append(savename)
                                create_world = False
                    if Cancel.is_down(event):
                        create_world = False
                    if cant_display:
                        sc.blit(Cant, (0, 0))
    if ingame:
        sc = pygame.display.set_mode((xSize, ySize), pygame.DOUBLEBUF | pygame.RESIZABLE | pygame.OPENGL)
        if Loadover___:
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            Loadover___ = False
        gluPerspective(45, (xSize / ySize), 0.1, 50.0)
        glTranslatef(0.0, 0.0, -5)
        Block("../../Resources/block/acacia_log")
    pygame.display.flip()